<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/9
 * Time: 16:58
 */

namespace app\home\controller;

use app\home\model\UserAddress;
use app\Request;


class Address
{

    /**
     * 添加和修改收货地址
     */
    public function addressEdit(Request $request)
    {
        $param = $request->param();
        $data = [
            'uid' => $request->userInfo['id'],
            'province_id' => $param['province_id'],
            'city_id' => $param['city_id'],
            'county_id' => $param['county_id'],
            'status' => $param['status'],
            'create_time' => time(),
            'address' => $param['address'],
            'province_name' => $param['province_name'],
            'city_name' => $param['city_name'],
            'county_name' => $param['county_name'],
            'phone' => $param['phone'],
            'name' => $param['name']

        ];
        $addressModel = new UserAddress();
        if ($param['status'] == 1) {
            $addressModel->where(['uid' => $request->userInfo['id']])->save(['status' => 2]);
        }

        if (isset($param['id']) && !empty($param['id'])) {
            $addressModel->where(['id' => $param['id']])->update($data);
        } else {
            $addressModel->insert($data);
        }
        return success('操作成功');
    }

    public function addressList(Request $request)
    {
        $addressModel = new UserAddress();
        $addressList = $addressModel->where('status', 'in', [1, 2])->where(['uid' => $request->userInfo['id']])->order('status', 'asc')->select();
        return success('收货地址列表', $addressList);
    }

    public  function getDefaultAddress(Request $request){
        $addressModel = new UserAddress();
        $addressList = $addressModel->where('status', '=', 1)->where(['uid' => $request->userInfo['id']])->find();
        return success('收货默认地址列表', $addressList);
    }

    public function setDefault(Request $request)
    {
        $param = $request->param();
        $addressModel = new UserAddress();
        $addressModel->where(['uid' => $request->userInfo['id']])->update(['status' => 2]);
        $addressModel->where(['uid' => $request->userInfo['id'], 'id' => $param['id']])->update(['status' => 1]);
        return success('修改成功');
    }

    public  function  delAddress(Request $request){
        $param = $request->param();
        $addressModel = new UserAddress();
        $addressModel->where(['uid' => $request->userInfo['id'], 'id' => $param['id']])->update(['status' => 3]);
        return success('修改成功');
    }
}
